package com.nursinghome.user.controller;

import com.nursinghome.bean.Elderly;
import com.nursinghome.bean.RespBean;
import com.nursinghome.exception.NurisingHomeException;
import com.nursinghome.user.service.ElderlyUserService;
import com.nursinghome.utils.JwtUtils;
import com.nursinghome.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping
public class UserLoginController {
    @Autowired
    private ElderlyUserService elderlyUserService;
    @Autowired
    private RedisUtil redisUtil;
    //登录认证
    @ResponseBody
    @PostMapping("/loginuser")
    public RespBean login(@NotBlank(message = "用户名不能为空") String eusername,
                          @NotBlank(message = "密码不能为空") String epassword,
                          @NotBlank(message = "验证码不能为空") String capath,
                          String capathID) throws NurisingHomeException {
        //判断验证码是否为空
        String capathIDRedis = (String)redisUtil.get(capathID);
        if ( capathIDRedis == null || (capathIDRedis != null && !capathIDRedis.equalsIgnoreCase(capath))){
            return RespBean.error("验证码错误或失效,请重新刷刷新");
        }
        Elderly elderly = elderlyUserService.selectByeusername(eusername, epassword);
        HashMap<String, Object> map = new HashMap<>();
        map.put("eid", elderly.getEid());
        map.put("eusername", elderly.getEusername());
        map.put("ename", elderly.getEname());
        map.put("character",3);

        String jwt = JwtUtils.generateJwt(map);

        return RespBean.ok("登录成功",jwt);
    }
}
